/*
 * @Author: your name
 * @Date: 2024-05-01 22:52:55
 * @LastEditTime: 2024-05-02 11:14:16
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \.leetcode\501.二叉搜索树中的众数.cpp
 */
/*
 * @lc app=leetcode.cn id=501 lang=cpp
 *
 * [501] 二叉搜索树中的众数
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    int maxCount = 0;
    int count = 0;
    TreeNode* pre_node = nullptr;
    void inorder(TreeNode* cur){
        
        if(cur == nullptr){
            return;
        }
        inorder(cur->left);
        // 计数
        if(pre_node == nullptr){
            // 第一个节点
            count = 1;
        }else if(cur->val == pre_node->val){
            // 当前节点与上一个节点一致
            count++;
        }else{
            // 当前节点与上一个节点不一致
            // 重置count
            count = 1;
        }
        // 更新上一个节点
        pre_node = cur;

        if(count == maxCount){
            res.push_back(cur->val);
        }
        if(count > maxCount){
            maxCount = count;
            res.clear();
            res.push_back(cur->val);
        }
        inorder(cur->right);

    }
    vector<int> findMode(TreeNode* root) {
        if(root == nullptr){
            return {};
        }
        inorder(root);
        return res;
    }
};
// @lc code=end

